package com.java1412.controller.api;

import com.java1412.utils.GenerateCodeUtil;
import com.java1412.utils.ResponseUtil;
import com.java1412.utils.SmsUtil;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import sun.misc.UUDecoder;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 发送验证码的控制器
 *
 * @author java1412
 * @since 2023-08-09 14:09:02
 */
@RestController
@RequestMapping(value = "/api/vc")
public class VerifyCodeController {
    @Resource
    private GenerateCodeUtil generateCodeUtil;

    @Resource
    private SmsUtil smsUtil;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @GetMapping(value = "/sendCode")
    public Object sendCode(String phone) {
        ResponseUtil r = null;
        try {
            // 生成验证码
            String code = generateCodeUtil.generateCode();
            System.out.println("验证码:" + code);
            // 调用SmsUtil发送验证码,这里省钱就不发送了
            // smsUtil.sendVerifyCode(phone, code);
            // 将手机号和验证码以及uuid（作为key）存到redis中，并设置过期时间
            String uuid = UUID.randomUUID().toString();
            // 存放的格式:uuid  ===> 手机号-验证码
            String phoneAndCode = phone + "-" + code;
            stringRedisTemplate.opsForValue().set(uuid, phoneAndCode);
            stringRedisTemplate.expire(uuid, 300, TimeUnit.SECONDS);
            Map<String, Object> map = new HashMap();
            map.put("uuid", uuid);
            // 响应给浏览器端的结果
            r = ResponseUtil.ok("短信验证码发送成功", map);
        } catch (Exception e) {
            e.printStackTrace();
            r = ResponseUtil.fail("短信验证码发送失败");
        }
        return r;
    }
}
